package com.fingersoft.im.utils

import android.content.Context
import android.util.Log
import com.fingersoft.app.bean.AppConfigInfo
import com.fingersoft.app.bean.IAppConfigProvider
import com.fingersoft.business.config.dao.updateFromDAO
import com.fingersoft.im.api.UserAgent
import com.fingersoft.im.api.base.BaseModelCallback2
import com.fingersoft.im.callback.AppConfigCallBack
import com.fingersoft.im.callback.AppInitInfoResponse
import com.fingersoft.realm.AppRealmUtils
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import okhttp3.Call
import okhttp3.Response
import java.util.concurrent.CountDownLatch

class AppConfigUtils(private val context: Context) : IAppConfigProvider {

    override fun getAppConfigInfo(): AppConfigInfo {
        return getAppConfigInfo(this.context)
    }

    companion object {
        val TAG = "AppConfigUtils"
        /**
         * 获取配置信息
         *
         * @param context
         * @return
         */
        @JvmStatic
        fun getAppConfigInfo(context: Context?): AppConfigInfo {
            val realm = AppRealmUtils.instance.getRealmNoCache(context)!!
            val appConfigInfo: AppConfigInfo? = realm.where(AppConfigInfo::class.java).equalTo("environment", AppUtils.J_ECODE).findFirst()
            if (appConfigInfo != null) {
                return realm.copyFromRealm(appConfigInfo)
            } else {
                return AppConfigInfo()
            }
        }


        /**
         * 拉取服务端配置
         *
         * @param context
         * @param callBack
         */
        @JvmStatic
        fun getAppConfig(context: Context, callBack: AppConfigCallBack?) {
            try {
                OkGo.post(AppUtils.getApiUrl("am/startup/getConfig", AppUtils.J_ECODE))
                    .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
                    .cacheMode(CacheMode.NO_CACHE)
                    .execute(object : BaseModelCallback2<AppInitInfoResponse>(AppInitInfoResponse::class.java) {
                        override fun onSuccess(appinitinforesponse: AppInitInfoResponse?, call: Call, response: Response) {
                            super.onSuccess(appinitinforesponse, call, response)
                            try {
                                if (AppUtils.showApiSucceedErrorToast(appinitinforesponse)) {
                                    throw Exception("response error")
                                }
                                if (null != appinitinforesponse) {
                                    dealAppConfigInfo(appinitinforesponse)
                                }
//                                val appInfo = appinitinforesponse.data
//                                val realm = AppRealmUtils.instance.getRealm(null)!!
//                                realm.beginTransaction()
//                                //查询配置
//                                var appconfiginfo: AppConfigInfo? = realm.where(AppConfigInfo::class.java).equalTo("environment", AppUtils.J_ECODE).findFirst()
//                                //没有用户则新建配置
//                                if (appconfiginfo == null) {
//                                    appconfiginfo = realm.createObject(AppConfigInfo::class.java, AppUtils.J_ECODE)
//                                }
//
//                                appconfiginfo!!.updateFromDAO(appInfo!!)
//
//                                realm.commitTransaction()
                                callBack?.onSuccess("success")
                            } catch (e: Exception) {
                                e.printStackTrace()
                                Log.i(TAG,"getAppConfig.onError:error is:${e.message}")
                                callBack?.onError("error")
                            }
                        }

                        override fun onError(call: Call?, response: Response?, e: Exception?) {
                            try {
                                AppRealmUtils.instance.closeRealmWithException()
                            } catch (e: Exception) {
                                e.printStackTrace()
                            } finally {
                                Log.i(TAG,"getAppConfig.onError:error is:${e?.message}")
                                callBack?.onError("error")
                            }
                        }
                    })
            } catch (e: Exception) {
                e.printStackTrace()
                Log.i(TAG,"getAppConfig.onError:error is:${e.message}")
                callBack?.onError(e.message ?: "error")
            }
        }
        fun dealAppConfigInfo(appInitInfoResponse: AppInitInfoResponse){
            val appInfo = appInitInfoResponse.data
            val realm = AppRealmUtils.instance.getRealmNoCache(null)!!
            realm.beginTransaction()
            //查询配置
            //没有用户则新建配置
            val appConfigInfo: AppConfigInfo = realm.where(AppConfigInfo::class.java).equalTo("environment", AppUtils.J_ECODE).findFirst() ?: realm.createObject(AppConfigInfo::class.java, AppUtils.J_ECODE)
            appConfigInfo.updateFromDAO(appInfo!!)
            realm.commitTransaction()
        }
        @JvmStatic
        fun getAppConfigSync(context: Context): Boolean {
            var result = false
            val modelResponse: AppInitInfoResponse? = getAppInitInfoResponseSync()
            try {
                if (modelResponse != null) {
                    if (AppUtils.showApiSucceedErrorToast(modelResponse)) {
                        throw Exception("response error")
                    }
                    dealAppConfigInfo(modelResponse)
                    result = true
                } else {
                    AppRealmUtils.instance.closeRealmWithException()
                }
            } catch (e: Exception) {
                Log.e("initAppConfig", e.message ?: "error", e)
            }
            return result
        }

        private fun getAppInitInfoResponseSync(): AppInitInfoResponse? {
            try {
                var modelResponse: AppInitInfoResponse? = null
                val latch = CountDownLatch(1)
                val thread = Thread {
                    try {
                        val response = OkGo.post(AppUtils.getApiUrl("am/startup/getConfig", AppUtils.J_ECODE))
                            .headers("Emp-Info", JSONUtils.toJsonString(UserAgent(AppUtils.getTokenInfo().userToken, AppUtils.getTokenInfo().did)))
                            .cacheMode(CacheMode.NO_CACHE)
                            .execute()

                        val callback = object : BaseModelCallback2<AppInitInfoResponse>(AppInitInfoResponse::class.java) {
                            override fun onError(call: Call?, response: Response?, e: Exception?) {
                            }
                        }
                        if (response.isSuccessful) {
                            modelResponse = callback.convertSuccess(response)
                        } else {
                            throw Exception("response error,code=${response.code()},message=${response.message()}")
                        }
                    } catch (e: Exception) {
                        Log.e("initAppConfig", e.message ?: "error", e)
                    } finally {
                        latch.countDown();
                    }
                }
                thread.start()
                try {
                    latch.await()
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                return modelResponse
            } catch (e: Exception) {
                return null
            }
        }
    }
}
